<style lang="less">
  .mButton {
    margin-bottom: 10px;
  }
</style>
<template>
  <section>
    <div class="table" style="float: left;margin-bottom: 10px;width: 49%">
      <el-button type="primary" @click="addTemplet" class="mButton">新增</el-button>
      <!--<el-button type="primary" @click="sendSMS" class="mButton" style="float: right">生成短信</el-button>-->
      <el-table :data="templetTableData" highlight-current-row border style="width: 100%;" height="600"
                ref="templetTableData"
                v-loading="templetListLoading"
                @current-change="handleCurrentChangeByTemplet">
        <el-table-column type="selection" width="50" align="center">
        </el-table-column>
        <el-table-column prop="templetTypeName" label="模板类型"  width="150" align="center" >
        </el-table-column>
        <el-table-column prop="aliSmsId" label="阿里模板ID"  width="150" align="center" >
        </el-table-column>
        <el-table-column prop="contentParams" label="模板参数" align="center" width="200" >
        </el-table-column>
        <el-table-column prop="content" label="模板内容" align="center" width="200" >
        </el-table-column>
        <el-table-column fixed="right"  label="操作" width="150" align="center">
          <template slot-scope="scope">
            <el-button type="primary" @click="editTemplet(scope.$index, scope.row)">编辑</el-button>
            <el-button type="danger" @click="deleteTemplet(scope.$index, scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="table" style="float: right;width: 49%">
      <el-button type="primary" @click="addScript" class="mButton">新增</el-button>
      <el-button type="danger" @click="batchDeleteScript" class="mButton">批量删除</el-button>
      <el-button type="primary" @click="handleNewMapping" class="mButton" style="float: right">保存映射</el-button>
      <el-table ref="scriptTableData" :data="scriptTableData" highlight-current-row border style="width: 100%;" height="600"
                v-loading="scriptListLoading"
                @selection-change="scriptSelsChange" >
        <el-table-column type="selection" width="50" align="center">
        </el-table-column>
        <el-table-column prop="beanName" label="实例名"  width="180" align="center" >
        </el-table-column>
        <el-table-column prop="methodName" label="方法名"  min-width="150" align="center" >
        </el-table-column>
        <el-table-column prop="scriptName" label="脚本名"  width="100" align="center" >
        </el-table-column>
        <el-table-column prop="paramName" label="参数名"  width="150" align="center" >
        </el-table-column>
        <el-table-column prop="remark" label="备注"  width="100" align="center" >
        </el-table-column>
        <el-table-column fixed="right"  label="操作" width="150" align="center">
          <template slot-scope="scope">
            <el-button type="primary" @click="editScript(scope.$index, scope.row)">编辑</el-button>
            <el-button type="danger" @click="deleteScript(scope.$index, scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :title="dialogTempletTitle" :visible.sync="dialogTempletVisible" size="tiny" :close-on-click-modal="false">
      <el-form :model="dialogTemplet" ref="dialogTemplet" :rules="templetRules" label-width="100px" style="width: 90%;margin: 0px auto">
        <el-form-item label="模板类型" prop="templetType" >
          <el-select v-model="dialogTemplet.templetType" placeholder="请选择模板类型" style="width: 220px" >
            <el-option
              v-for="item in $store.getters.SMS_TEMPLATE_TYPE"
              :label="item.cnDictValname"
              :key="item.dictVal"
              :value="item.dictVal">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阿里模板ID" prop="aliSmsId">
          <el-input v-model="dialogTemplet.aliSmsId" placeholder="请输入阿里模板ID"  style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="模板参数" prop="contentParams">
          <el-input type="textarea" :rows="3" placeholder='示例：{"name":"NE"，"orderNumber":"ON"}' v-model="dialogTemplet.contentParams"></el-input>
        </el-form-item>
        <el-form-item label="模板内容" prop="content">
          <el-input type="textarea" :rows="4" placeholder="变量格式：${name}；
示例：尊敬的${name}，您的订单号为:${name}的货物已经完成签收，签收人：${time}。" v-model="dialogTemplet.content"></el-input>
        </el-form-item>
        <div style="margin-bottom: 30px">
        <el-button @click="cancelDialogTemplet"  style="float: right;" class="mButton" >取 消</el-button>
        <el-button type="primary" @click="handleSubmitTemplet" :loading="templetSubmitLoading" style="float: right;margin-right: 5px;" class="mButton">提交</el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog :title="dialogScriptTitle" :visible.sync="dialogScriptVisible" size="tiny" :close-on-click-modal="false" width="600px">
      <el-form :model="dialogScript" ref="dialogScript" :rules="scriptRules" label-width="150px" style="width: 90%;margin: 0px auto">
        <el-form-item label="实例名" prop="beanName" >
          <el-input v-model="dialogScript.beanName" style="width: 220px" placeholder="请输入实例名"></el-input>
        </el-form-item>
        <el-form-item label="方法名" prop="methodName" >
          <el-input v-model="dialogScript.methodName" style="width: 220px" placeholder="请输入方法名"></el-input>
        </el-form-item>
        <el-form-item label="脚本名" prop="scriptName" >
          <el-input v-model="dialogScript.scriptName" style="width: 220px" placeholder="请输入脚本名"></el-input>
        </el-form-item>
        <el-form-item label="参数名" prop="paramName" >
          <el-input v-model="dialogScript.paramName" style="width: 220px" placeholder="请输入参数名"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark" >
          <el-input type="textarea" :rows="4" style="width: 220px"  v-model="dialogScript.remark" placeholder="请输入参数名"></el-input>
        </el-form-item>
      </el-form>
      <div  class="dialog-footer" style="margin-bottom: 30px">
        <el-button @click.native="cancelDialogScript"  style="float: right;" class="mButton">取 消</el-button>
        <el-button type="primary" @click.native="handleSubmitScript" :loading="scriptSubmitLoading" style="float: right;margin-right: 5px" class="mButton">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import {getSmsTemplets, getSmsScripts, saveSmsTemplet, saveSmsScript, deleteSmsTemplet, deleteSmsScript, getMappingByTempletId, postNewMapping, modifySmsTemplet} from '../../api/v3/SmsTemplet.js';
export default {
  data () {
    return {
      token: this.$store.state.token,
      // 短信脚本复选框选中数据
      scriptSels: [],
      // 短信模板列表数据
      templetTableData: [],
      // 短信脚本列表数据
      scriptTableData: [],
      // 模板列表数据加载中属性
      templetListLoading: false,
      // 模板增加/修改加载中属性
      templetSubmitLoading: false,
      // 短信脚本数据列表加载中属性
      scriptListLoading: false,
      // 短信脚本增加/修改加载中属性
      scriptSubmitLoading: false,
      // 用户列表弹出框标题
      //        dialogSendSMSTitle: '会员列表',
      // 分页设置
      currentPage: 1,
      pageSize: 100,
      userCurrentPage: 1,
      userPageSize: 10,
      // 模板对话框标题及内容默认为空
      dialogTempletTitle: null,
      dialogTemplet: {
        templetType: null,
        aliSmsId: null
      },
      // 用户列表查询条件
      condition: {
        LIKE_userName: null,
        EQ_phone: null,
        LIKE_email: null
      },
      userListLoading: false,
      total: 0,
      userSels: [],
      // 短信模板dialog默认不显示
      dialogTempletVisible: false,
      templetRules: {
        templetType: [
          {required: true, message: '请选择模板类型'}
        ],
        aliSmsId: [
          {required: true, message: '请输入阿里模板ID'}
        ],
        content: [
          {required: true, message: '请输入模板内容'}
        ]
      },
      // 脚本对话框标题及内容默认为空
      dialogScriptTitle: null,
      dialogScript: {
        beanName: null,
        methodName: null,
        scriptName: null
      },
      // 脚本dialog默认不显示
      dialogScriptVisible: false,
      scriptRules: {
        beanName: [
          {required: true, message: '请输入实例名'}
        ],
        methodName: [
          {required: true, message: '请输入方法名'}
        ],
        scriptName: [
          {required: true, message: '请输入脚本名'}
        ],
        paramName: [
          {required: true, message: '请输入参数名'}
        ]
      },
      selectedRow: null
    };
  },
  methods: {
    // 选择改变事件（包括全选/全不选、单选/单取消）传入的值为选中的复选框）
    scriptSelsChange (scriptSels) {
      this.scriptSels = scriptSels;
    },
    // 新增短信模板
    addTemplet () {
      this.resetDialogTemplet();
      this.dialogTempletTitle = '新增短信模板';
      this.dialogTempletVisible = true;
      this.dialogTemplet.id = null;
    },
    // 修改短信模板
    editTemplet (index, row) {
      this.resetDialogTemplet();
      this.dialogTempletTitle = '修改短信模板';
      this.dialogTempletVisible = true;
      this.dialogTemplet.aliSmsId = row.aliSmsId;
      this.dialogTemplet.id = row.id;
      this.dialogTemplet.contentParams = row.contentParams;
      this.dialogTemplet.content = row.content;
      this.dialogTemplet.remark = row.remark;
      this.dialogTemplet.templetType = parseInt(row.templetType);
    },
    // 新增/修改短信模板窗口的取消按钮
    cancelDialogTemplet () {
      this.dialogTempletVisible = false;
    },
    // 新增/修改短信模板窗口提交按钮
    handleSubmitTemplet () {
      this.$refs['dialogTemplet'].validate((valid) => {
        if (valid) {
          if (this.dialogTemplet.id === null) {
            this.templetSubmitLoading = true;
            saveSmsTemplet(this.dialogTemplet).then((res) => {
              this.templetSubmitLoading = false;
              if (res.data) {
                this.dialogTempletVisible = false;
                this.$message.success(this.dialogTempletTitle + '成功！');
                this.getTempletTableData();
              }
            });
          } else {
            this.templetSubmitLoading = true;
            modifySmsTemplet(this.dialogTemplet).then((res) => {
              this.templetSubmitLoading = false;
              if (res.data) {
                this.dialogTempletVisible = false;
                this.$message.success(this.dialogTempletTitle + '成功！');
                this.getTempletTableData();
              }
            });
          }
        }
      });
    },
    // 删除短信模板
    deleteTemplet (index, id) {
      this.$confirm('确认删除该短信模板吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.templetListLoading = true;
        deleteSmsTemplet(id).then((res) => {
          this.templetListLoading = false;
          this.$message({
            message: '删除成功！',
            type: 'success'
          });
          this.getTempletTableData();
        });
      });
    },
    // 根据模板id获取脚本
    handleCurrentChangeByTemplet (val) {
      this.$refs.scriptTableData.clearSelection();
      this.selectedRow = val;
      getMappingByTempletId(val.id).then((res) => {
        if (res.data.length > 0) {
          let ids = res.data.map(o => o.variableId);
          this.scriptTableData.forEach(item => {
            if (ids.indexOf(item.id) > -1) {
              this.$refs.scriptTableData.toggleRowSelection(item, true);
            }
          });
        }
      }).catch(() => {
        console.log();
      });
    },
    // 新增短信脚本
    addScript () {
      this.resetDialogScript();
      this.dialogScriptVisible = true;
      this.dialogScriptTitle = '新增短信脚本';
    },
    // 修改短信脚本
    editScript (index, row) {
      this.dialogScriptTitle = '修改短信脚本';
      this.resetDialogScript();
      this.dialogScriptVisible = true;
      this.dialogScript = Object.assign({}, row);
    },
    // 新增/修改脚本窗口的取消按钮
    cancelDialogScript () {
      this.dialogScriptVisible = false;
    },
    // 新增/修改脚本窗口提交按钮
    handleSubmitScript () {
      this.$refs['dialogScript'].validate((valid) => {
        if (valid) {
          this.scriptSubmitLoading = true;
          saveSmsScript(this.dialogScript).then((res) => {
            this.scriptSubmitLoading = false;
            if (res.data) {
              this.dialogScriptVisible = false;
              this.$message.success(this.dialogScriptTitle + '成功！');
              this.getScriptTableData();
            } else {
              this.$message.error(res.data.errorMsg);
            }
          }).catch(function (error) {
            console.log(error);
          });
        } else {
          this.$message({
            message: '填写数据有误！',
            tyep: 'error'
          });
        }
      });
    },
    // 删除脚本
    deleteScript (index, id) {
      this.$confirm('确认删除该短信脚本吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.scriptListLoading = true;
        deleteSmsScript(id).then((res) => {
          this.scriptListLoading = false;
          this.$message({
            message: '恭喜删除成功！',
            type: 'success'
          });
          this.getScriptTableData();
        });
      }).catch(() => {
        console.log();
      });
    },
    // 批量删除脚本
    batchDeleteScript () {
      let id = this.scriptSels.map(item => item.id);
      if (id.length === 0) {
        this.$message.error('请选择数据！');
      }
      this.$confirm('确认要批量删除选中模板吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.scriptListLoading = true;
        deleteSmsScript(id.join(',')).then((res) => {
          this.scriptListLoading = false;
          this.$message({
            message: '恭喜删除成功！',
            type: 'success'
          });
          this.getScriptTableData();
        });
      });
    },
    // 获取模板列表
    getTempletTableData () {
      this.templetListLoading = true;
      getSmsTemplets({
        token: this.token,
        page: this.currentPage - 1,
        size: this.pageSize
      }).then((res) => {
        if (res.data) {
          this.templetTableData = res.data;
          this.templetListLoading = false;
        }
      });
    },
    // 获取脚本列表
    getScriptTableData () {
      this.scriptListLoading = true;
      getSmsScripts({
        token: this.token,
        page: this.currentPage - 1,
        size: this.pageSize
      }).then((res) => {
        if (res.data) {
          this.scriptTableData = res.data;
          this.scriptListLoading = false;
        }
      });
    },
    // 保存映射
    handleNewMapping () {
      let templets = this.selectedRow.id;
      let variables = this.scriptSels.map(item => item.id);
      postNewMapping(templets, variables.join(',')).then((res) => {
        if (res.data) {
          this.$message({
            message: '保存成功',
            type: 'success'
          });
        }
      });
    },
    // 重置表单
    resetDialogTemplet () {
      if (this.$refs.dialogTemplet) {
        this.$refs.dialogTemplet.resetFields();
      }
      for (let p in this.dialogTemplet) {
        if (this.dialogTemplet[p] instanceof Array) {
          this.dialogTemplet[p] = [];
        } else {
          this.dialogTemplet[p] = null;
        }
      }
    },
    resetDialogScript () {
      if (this.$refs.dialogScript) {
        this.$refs.dialogScript.resetFields();
      }
      for (let p in this.dialogScript) {
        if (this.dialogScript[p] instanceof Array) {
          this.dialogScript[p] = [];
        } else {
          this.dialogScript[p] = null;
        }
      }
    }
  },
  mounted () {
    this.getTempletTableData();
    this.getScriptTableData();
    this.$store.commit('initDict');
  }
};
</script>
